package com.yangxk.kadmin.web.module.system.controller;

import com.yangxk.kadmin.common.beans.Result;
import com.yangxk.kadmin.common.exception.BizException;
import com.yangxk.kadmin.common.exception.UnLoginException;
import com.yangxk.kadmin.web.common.Const;
import com.yangxk.kadmin.web.common.SessionUserHolder;
import com.yangxk.kadmin.web.module.system.form.LoginForm;
import com.yangxk.kadmin.web.module.system.po.Auth;
import com.yangxk.kadmin.web.module.system.po.User;
import com.yangxk.kadmin.web.module.system.service.UserService;
import com.yangxk.kadmin.web.module.system.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * create by yangxk on 2018/9/13 17:09
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm, HttpServletRequest request) {
        User user = null;
        try {
            user = userService.checkLogin(loginForm);
        } catch (BizException e) {
            return Result.ofError(e.getBaseExceptionEnum());
        }

        // 功能权限
        List<Auth> authList = userService.findUserAuth(user.getId());
        List<String> collect = authList.stream().map(Auth::getAuthCode).collect(Collectors.toList());

        // 数据权限
        List<Long> ds = userService.findUserDataScope(user.getId());

        request.getSession().setAttribute(Const.SESSION_USER_KEY, user);
        request.getSession().setAttribute(Const.SESSION_USER_AUTH_KEY, collect);
        request.getSession().setAttribute(Const.SESSION_USER_DATA_SCOPE_KEY, ds);

        return Result.ofSuccess();
    }

    /**
     * 退出
     * create by yangxk on 2018/9/13 17:09
     */
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return Result.ofSuccess();
    }

    /**
     * 获取登录用户信息
     * create by yangxk on 2018/9/13 17:10
     */
    @GetMapping("/userinfo")
    public Result<UserVo> userinfo(HttpServletRequest request) {
        User user = (User)request.getSession().getAttribute(Const.SESSION_USER_KEY);
        return Result.ofSuccess(userService.findById(user.getId()));
    }

    @GetMapping("/unlogin")
    public Result unlogin() {
        throw new UnLoginException();
    }

    /**
     * 获取当前登录用户的权限信息
     * create by yangxk on 2018/9/21 16:56
     */
    @GetMapping("/authinfo")
    public Result userAuth() {
        long userId = SessionUserHolder.getUserId();
        return Result.ofSuccess(userService.findAuthTreeOfUser(userId));
    }
}
